import turbogears as tg
from turbogears import controllers, expose, flash
from turbogears import identity, redirect
from cherrypy import request, response

from subcontrollers.article_controller import Article
from subcontrollers.article_controller import ArticleEditor
from subcontrollers.articlemanager_controller import ArticleManager
from subcontrollers.articlelist_controller import ArticleList

# from model import *
# import logging
# log = logging.getLogger("blockarticle.controllers")

class Root(controllers.RootController):
    @expose(template="blockarticle.templates.welcome")
    def index(self):
        raise redirect(tg.url('/article_list/'))
    
    @expose(template="blockarticle.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            raise redirect(tg.url(forward_url))

        forward_url=None
        previous_url= tg.url(request.path)

        if identity.was_login_attempted():
            msg=_("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg=_("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg=_("Please log in.")
            forward_url= request.headers.get("Referer", "/")
            
        response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)

    @expose()
    def logout(self):
        identity.current.logout()
        raise redirect(tg.url("/"))

    article = Article()
    article_editor = ArticleEditor()
    
    article_manager = ArticleManager()
    
    article_list = ArticleList()